package com.lancoo.answer.view.fragment.composition.answer;

import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lancoo.answer.R;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.util.SoftInputUtils;
import com.rxjava.rxlife.RxLife;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/8 14:15
 * Description:
 */
public class CompositionPencilAnswerFragment extends Fragment {
    private View converView;

    private Item item;
    private EditText editText;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        converView=inflater.inflate(R.layout.ev_fragment_composition_answer_type_pencil,container,false);
        return converView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }


    public static Fragment loadFragment(int kindIndex, int queseIndex, int smallQueseIndex){

        CompositionPencilAnswerFragment fragment=new CompositionPencilAnswerFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt("kindIndex",kindIndex);
        mBundle.putInt("queseIndex",queseIndex);
        mBundle.putInt("smallQueseIndex",smallQueseIndex);
        fragment.setArguments(mBundle);
        return fragment;
    }

    public void setItem(Item item){
        this.item=item;
    }

    private void initView(View view){
//        if(item==null){
//            return;
//        }
        int kindIndex = getArguments().getInt("kindIndex");
        int queseIndex = getArguments().getInt("queseIndex");
        int smallQueseIndex = getArguments().getInt("smallQueseIndex");
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        item = kindBeanListk.get(kindIndex).getQuesList().get(queseIndex)
                .getChildList().get(smallQueseIndex).getItemList().get(0);

        editText = view.findViewById(R.id.edittext);
        editText.setText(item.getStuAnswer());
        SoftInputUtils.setEditTextInputSpace(editText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                item.setStuAnswer(editable.toString().trim());
                updateAnswerCount();
            }
        });

        updateAnswerCount();
    }

    /**
     * 统计作答个数
     */
    private void updateAnswerCount(){
        TextView tv_answerCount=converView.findViewById(R.id.tv_answer_count);

        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    int count=0;
                    if(!TextUtils.isEmpty(item.getStuAnswer())){
                        String[] split = item.getStuAnswer()
                                .replace("\n"," ")
                                .split(" ");
                        count=split.length;
                        for (int i = 0; i < split.length; i++) {
                            String str=split[i];
                            if(str.isEmpty()){
                                count--;
                            }
                        }
                    }
                    emitter.onNext(Math.max(count,0));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(integer -> {

                    SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                    spannableStringBuilder.append("Word Count:");
                    SpannableString spannableString=new SpannableString(""+integer);
                    spannableString.setSpan(new ForegroundColorSpan(0xff666666),0,spannableString.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    tv_answerCount.setText(spannableStringBuilder);
                }, throwable -> {});
    }

    public void updateKeyboardShowState(boolean isShow){
        if(!isShow){
            return;
        }
        Single.timer(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {
                    if(editText!=null){
                        editText.requestFocus();
                    }
                });

    }

}
